//
//  LoginViewController.m
//  SITABLE
//
//  Created by songjun on 16/9/27.
//  Copyright © 2016年 Sita. All rights reserved.
//

#import "LoginViewController.h"

@interface LoginViewController ()

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    phoneNumberTf.delegate = self;
    passWordTf.delegate = self;
    
    //注册成功的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(registerSuccessNotyAction:) name:@"registerSuccessNoty" object:nil];
    
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesAction:)];
    [self.view addGestureRecognizer:tapGes];
    
    phoneNumberTf.returnKeyType = UIReturnKeyDone;
    passWordTf.returnKeyType =UIReturnKeyDone;
}



- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    //NSLog(@"点击了搜索");
    return YES;
}

-(void)registerSuccessNotyAction:(NSNotification *)noty
{
    ResisterObj *resistObi = noty.object;
    if (resistObi) {
        phoneNumberTf.text = resistObi.mobile;
        passWordTf.text = resistObi.imPassword;
    }
}


//单击收回键盘
-(void)tapGesAction:(UITapGestureRecognizer *)ges
{
    
    [passWordTf resignFirstResponder];
    [phoneNumberTf resignFirstResponder];
    
    
}

#pragma mark -----texfield代理----
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    
    
}


//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    float duaration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    [UIView animateWithDuration:duaration animations:^{
        self.view.frame = CGRectMake(0, -height/4, SCREEN_WIDTH, SCREEN_HEIGHT);
    }];
}

//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    float duaration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    [UIView animateWithDuration:duaration animations:^{
        self.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    }];
}


-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    [phoneNumberTf setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
    [passWordTf setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
    
    pwdIv.layer.borderWidth = 1.0;
    pwdIv.layer.borderColor = [UIColor lightGrayColor].CGColor;
    
    phoNumberIv.layer.borderColor =[UIColor lightGrayColor].CGColor;
    phoNumberIv.layer.borderWidth = 1.0;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
     [self.navigationController setNavigationBarHidden:YES animated:animated];
}



- (IBAction)loginAction:(UIButton *)sender
{
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
    hud.labelText = @"登录中......";
    hud.tag = 1302;
    hud.mode =MBProgressHUDModeText;
    [self.view addSubview:hud];
    [hud show:YES];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    //[manager.requestSerializer set]
    [manager.requestSerializer setTimeoutInterval:10.0f];
    NSString *mUrl = [NSString stringWithFormat:@"%@%@",linboardBaseUrl,linboardLogin];
    NSDictionary *parametersDic = [NSDictionary dictionaryWithObjectsAndKeys:phoneNumberTf.text,@"mobile",passWordTf.text,@"password",nil];
    //NSLog(@"****:%@",parametersDic);
    
    [manager POST:mUrl parameters:parametersDic progress:^(NSProgress * _Nonnull uploadProgress) {
        ;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *errorcode = [responseObject valueForKey:@"errorCode"];
        if ([errorcode isEqualToString:@"0"]) {
            NSDictionary *infdic = [[responseObject valueForKey:@"data"] valueForKey:@"account"];
            //NSLog(@"哈哈:%@",infdic);
            
            ResisterObj *bettryInfo = [ResisterObj mj_objectWithKeyValues:infdic];
            
            [[NSUserDefaults standardUserDefaults] setValue:bettryInfo.accountId forKey:@"pallaAccountId"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [[NSUserDefaults standardUserDefaults] setValue:bettryInfo.avatar forKey:@"pallaAvatar"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [[NSUserDefaults standardUserDefaults] setValue:[NSString stringWithFormat:@"%d",bettryInfo.gender] forKey:@"pallaGender"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [[NSUserDefaults standardUserDefaults] setValue:bettryInfo.mobile forKey:@"pallaMobile"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [[NSUserDefaults standardUserDefaults] setValue:bettryInfo.imPassword forKey:@"pallaImPassword"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [[NSUserDefaults standardUserDefaults] setValue:bettryInfo.nickName forKey:@"pallaNickName"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"loginNoty" object:nil];
            [hud removeFromSuperview];
            
                    }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //        NSData *dicdata=[[error userInfo] valueForKey:@"com.alamofire.serialization.response.error.data"];
        //        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:dicdata options:NSJSONReadingMutableContainers error:nil];
        //        NSLog(@"****:%@",dic);
        hud.labelText = @"登录失败!";
        [self performSelector:@selector(dismissHud1302) withObject:nil afterDelay:1.5f];
        ;
    }];
    
    
}


- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}


-(void)dismissHud1302
{
    MBProgressHUD *hud = [self.view viewWithTag:1302];
    if (hud) {
        [hud removeFromSuperview];
    }
}


- (IBAction)newUserRegisterAction:(UIButton *)sender
{
    
    RegisterViewController *loginVc = [[UIStoryboard storyboardWithName:@"LoginRegisterSb" bundle:nil] instantiateViewControllerWithIdentifier:@"registerVc"];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
    backItem.title = @"";
    self.navigationItem.backBarButtonItem = backItem;
    [self.navigationController pushViewController:loginVc animated:YES];
    
}


- (IBAction)forgetPwdAction:(UIButton *)sender
{
    ForgetPwdViewController *loginVc = [[UIStoryboard storyboardWithName:@"LoginRegisterSb" bundle:nil] instantiateViewControllerWithIdentifier:@"forgePwdVc"];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
    backItem.title = @"";
    self.navigationItem.backBarButtonItem = backItem;
    [self.navigationController pushViewController:loginVc animated:YES];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
